﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
using WCF;
using System.Data;

namespace geekmeet
{
    /// <summary>
    /// The page that show the friends of a user, with fields that holds info about the logged in 
    /// user and the profile that is being viewed.
    /// </summary>
    public partial class Friends : System.Web.UI.Page
    {
        protected string currentFriend;
        protected GeekMeetService wcf = new GeekMeetService();
        Guid loggedInUserGUID;
        Guid viewUserID;
        string viewUserName;


        protected void Page_Load(object sender, EventArgs e)
        {
            //Check if user is logged in
            if (User.Identity.IsAuthenticated)
            {
                loggedInUserGUID = (Guid)Membership.GetUser().ProviderUserKey;
                SetViewUserID();
                GetFriends();
                GetNewFriends();
                GetUserName();
                DisplayUserNameHeader();
                EditSitemap();

                if (viewUserID != loggedInUserGUID)
                    GetNewFriends();

                if (Request.QueryString["action"] == "confirmFriend")
                    ConfirmFriend();
            }
        }

        /// <summary>
        /// Change sitemap root node text to username 
        /// </summary>
        private void EditSitemap()
        {
            // Show sitemap in format username > page
            SiteMap.CurrentNode.ParentNode.ReadOnly = false;
            SiteMap.CurrentNode.ParentNode.Title = viewUserName;
            SiteMap.CurrentNode.ParentNode.Url = "Profile.aspx?user=" + viewUserID.ToString();
        }


        /// <summary>
        /// Displays the title of the friendspage
        /// </summary>
        private void DisplayUserNameHeader()
        {
            string loggedInUserName = Membership.GetUser().UserName;
            //If I am looking at my own friendlist 
            if (viewUserName == loggedInUserName)
                lblUsername.Text = "Mina vänner";
            else
            {
                //Check if username ends with 'S', if not, append s to user name + 'vänner'
                bool endsWithS = (viewUserName[viewUserName.Length - 1] == 's' ? true : false);
                lblUsername.Text = (endsWithS == false ? viewUserName + "s" : viewUserName);
                lblUsername.Text += " vänner";
            }
        }

        private void GetUserName()
        {
            viewUserName = wcf.GetUserName(viewUserID);
        }

        /// <summary>
        /// Checks who is viewing the page
        /// </summary>
        private void SetViewUserID()
        {
            if (Request.QueryString != null && Request.QueryString["user"] != null)
            {
                try
                {
                    viewUserID = Guid.Parse(Request.QueryString["user"]);
                }

                catch
                {
                    Response.Redirect("~/Error404.aspx");
                }
            }

            else
                viewUserID = loggedInUserGUID;

        }

        /// <summary>
        /// Handles a users respond to a friend request
        /// </summary>
        private void ConfirmFriend()
        {
            try
            {
                //Is the user accepting or not? 
                bool isAccepted = bool.Parse(Request.QueryString["accept"]);
                Guid requestFromID = Guid.Parse(Request.QueryString["user"]); // ID of friend requesting user

                // Try updating database
                bool success = wcf.ConfirmFriend(requestFromID, loggedInUserGUID, isAccepted);

                if (success)
                    Response.Redirect("Friends.aspx");
            }
            catch (Exception ex)
            {
                Response.Redirect("Friends.aspx");
            }

        }

        /// <summary>
        /// Gets gender fron a user
        /// </summary>
        /// <param name="userID"></param>
        /// <returns>string with gender info</returns>
        protected string GetGender(string userID)
        {
            Guid userToRequest;

            try
            {
                userToRequest = Guid.Parse(userID);
                return wcf.GetGender(userToRequest).ToString();
            }
            catch
            {
                return null;
            }

        }

        /// <summary>
        /// Displays the new friends to a user
        /// </summary>
        private void GetNewFriends()
        {
            List<FriendComposite> newFriends = (List<FriendComposite>)wcf.GetNewFriends(loggedInUserGUID);

            if (newFriends.Count > 0)
            {
                newFriendRepeater.DataSource = newFriends;
                newFriendRepeater.DataBind();
                panNewFriends.Visible = true;
            }
            else
                panNewFriends.Visible = false;
        }

        /// <summary>
        /// Gets all the friends from a user
        /// </summary>
        private void GetFriends()
        {
            List<FriendComposite> allFriends = new List<FriendComposite>();
            allFriends = wcf.GetFriends(viewUserID);
            int numberOfFriends = allFriends.Count;
            //Gets all categories, using lambda expression that selects the distinct categories from the list
            var uniqueCategories = allFriends.Select(f => f.FriendCategoryName).Distinct().ToList();
            int numberOfCategories = uniqueCategories.Count;

            catRepeater.DataSource = uniqueCategories;
            catRepeater.DataBind();

            foreach (RepeaterItem repeaterItem in catRepeater.Items)
            {
                string currentFriendCategory =
                    ((HiddenField)repeaterItem.FindControl("hiddenCurrentCat")).Value;

                // Find all friends of current category
                var friends = allFriends.Where(fr =>
                    fr.FriendCategoryName.Equals(currentFriendCategory));


                ((Repeater)(repeaterItem.FindControl("friendRepeater"))).DataSource = friends;
                ((Repeater)(repeaterItem.FindControl("friendRepeater"))).DataBind();
            }
        }

    }
}